﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Convertor.Interface;
using Convertor.Plugin;

namespace Convertor
{
    /// <summary>
    /// LoadConfigWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LoadConfigWindow : Window, IFormGetConfigEvent
    {
        private IPluginItem pluginContent;

        public IPluginItem PluginContent
        {
            get { return pluginContent; }
        }

        private object plugin;
        private PluginConfigForm configControl;
        private List<HistoryContent> historyList;
        private IConvertParamters output;
        private ConvertDelegate convertFun;

        public LoadConfigWindow()
        {
            InitializeComponent();
            testLoader.Visibility = System.Windows.Visibility.Collapsed;
            memoLoader.Visibility = System.Windows.Visibility.Collapsed;
        }

        public LoadConfigWindow(IPluginItem pluginContent, object plugin, IConvertParamters output, ConvertDelegate convertFun)
            : this()
        {
            this.Title = pluginContent.Name;
            this.pluginContent = pluginContent;
            this.plugin = plugin;
            this.output = output;
            this.convertFun = convertFun;
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            configControl = (plugin as PluginBase).ConfigForm;
            if (configControl != null)
            {
                configControl.Config = pluginContent.Config;
                configControl.ParentWindow = this;

                PluginLoader.SetValue(ContentPresenter.ContentProperty, null);
                configControl.Margin = new Thickness(5);
                PluginLoader.Children.Add(configControl);

                try
                {
                    historyList = Wpf.CommonTools.FileExtension.Processing.LoadFile<List<HistoryContent>>(Config.InputHistoryPath);
                }
                catch
                {
                    historyList = new List<HistoryContent>();
                }
                configControl.InputHistory = historyList.Where(p => p.Path == pluginContent.Path).Select(p => p.Hisotry).ToList();

                IPluginTemplateList iTemplate = configControl as IPluginTemplateList;
                if (iTemplate != null)
                {
                    iTemplate.AllTemplate = Config.GlobalConfig.TemplateList;
                }
                //Color c = Colors.Black;
                //c.A = 0; 
                //configControl.Background = new SolidColorBrush(c);
            }
            else
            {
                Button_OpenTest_Click(btOpenTest, new RoutedEventArgs());
            }
            try
            {
                tbInput.Text = output.OutputContent.ToString();
            }
            catch { }
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
        }

        private bool close;
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (Config.GlobalConfig.EnableEscToCloseChildWindows && this.IsActive && e.Key == Key.Escape)
            {
                close = true;
            }
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            if (close && Config.GlobalConfig.EnableEscToCloseChildWindows && this.IsActive && e.Key == Key.Escape)
            {
                this.Close();
            }
        }

        private void Button_OK_Click(object sender, RoutedEventArgs e)
        {
            setConfig();
            saveHistory();

            this.DialogResult = true;
            this.Close();
        }

        private void Button_Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Button_Test_Click(object sender, RoutedEventArgs e)
        {
            startTest();
        }

        private void Button_OpenTest_Click(object sender, RoutedEventArgs e)
        {
            toggleVisible(sender, testLoader, memoLoader);

        }

        private void Button_OpenMemo_Click(object sender, RoutedEventArgs e)
        {
            toggleVisible(sender, memoLoader, testLoader);
        }

        private void toggleVisible(object sender, FrameworkElement toShow, FrameworkElement toHide)
        {
            toHide.Visibility = System.Windows.Visibility.Collapsed;

            var children = ((System.Windows.Controls.Panel)(((System.Windows.Controls.ContentControl)(sender)).Content)).Children;
            Image image = children[1] as Image;

            if (toShow.Visibility == System.Windows.Visibility.Collapsed)
            {
                toShow.Visibility = System.Windows.Visibility.Visible;
                ((System.Windows.Media.RotateTransform)(((System.Windows.UIElement)(image)).RenderTransform)).Angle = 0;
            }
            else
            {
                toShow.Visibility = System.Windows.Visibility.Collapsed;
                ((System.Windows.Media.RotateTransform)(((System.Windows.UIElement)(image)).RenderTransform)).Angle = 180;
            }

            toShow.MinWidth = 600;
            toShow.MaxWidth = this.Width - 10;
            toShow.MaxHeight = testLoader.MinHeight = 300;
        }

        private void startTest()
        {
            setConfig();
            output = new ConvertParamters(tbInput.Text, tbInput.Text);
            tbOutput.Text = string.Empty;
            Thread th = new Thread(new ThreadStart(() =>
            {
                IConvertParamters content = convertFun(output, pluginContent);
                tbOutput.Dispatcher.Invoke(() =>
                {
                    if (content.OutputContent != null)
                    {
                        IList e;
                        if ((e = (content.OutputContent as IList)) != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            int k = 0;
                            foreach (var item in e)
                            {
                                k++;
                                if (k < 10000)
                                {
                                    sb.AppendLine(item == null ? "object.NULL" : item.ToString());
                                }
                            }
                            int m = Math.Min(3, k - 1000);
                            if (m > 0)
                            {
                                sb.AppendLine("...");
                                for (int i = m; i > 0; i--)
                                {
                                    sb.AppendLine(e[e.Count - i].ToString());
                                }
                            }

                            tbOutput.Text = sb.ToString();
                        }
                        else
                        {
                            tbOutput.Text = content.OutputContent.ToString();
                        }
                    }
                    else
                    {
                        tbOutput.Text = "object.NULL";
                    }
                });
                Config.ProcesingPluginNameModel.ProcessingPluginName = string.Empty;
            }));
            //th.SetApartmentState(ApartmentState.STA);
            th.IsBackground = true;
            th.Start();
        }

        private void setConfig()
        {
            IPluginConfigForm iFrom = plugin as IPluginConfigForm;
            if (iFrom != null)
            {
                pluginContent.Config = ((IFormGetConfigEvent)configControl).GetConfig();
            }
        }

        private void saveHistory()
        {
            var input = configControl.Input;
            HistoryContent content = new HistoryContent() { Path = pluginContent.Path, Hisotry = input };
            if (!historyList.Contains(content))
            {
                var history = historyList.Where(p => p.Path == pluginContent.Path).ToList();
                if (history.Count > 15)
                {
                    historyList.Remove(history[history.Count - 1]);
                }
                historyList.Insert(0, content);
            }
            else
            {
                historyList.Remove(content);
                historyList.Insert(0, content);
            }
            try
            {
                Wpf.CommonTools.FileExtension.Processing.SaveFile(historyList, Config.InputHistoryPath);
            }
            catch
            {
            }
        }

        #region IConfigFormEvent 成员

        object IFormGetConfigEvent.GetConfig()
        {
            return pluginContent.Config;
        }

        #endregion
    }
}
